package com.teamwings.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HttpHelper {

	/**
	 * 处理POST/PUT请求,转换bodyString
	 * @param request /
	 * @return /
	 */
	public static String getBodyString(HttpServletRequest request) {
		StringBuilder sb = new StringBuilder();
		String result = "";
		String regex = "codeParams";
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
			String line;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			result = sb.toString();
			if (StringUtils.isNotBlank(result)) {
				// 数据处理
				if (isJson(result)) {
					Map<String, Object> ts = JSON.parseObject(result);
					// 加密
					if (ts.get(regex) != null) {
						String encryptCipher = ts.get(regex).toString();
						String enc = EncryptUtil.desEncrypt(encryptCipher);
						result = URLDecoder.decode(enc, "UTF-8");
					}
				}
			}
		} catch (Exception e) {
			log.error("参数获取异常");
		}
		return result;
	}

	/**
	 * bodyString Map
	 * @param bodyString /
	 * @return /
	 */
	public static Map<String, String[]> getBodyMap(String bodyString) {
		Map<String, String[]> r = new HashMap<>(16);
		if (isJson(bodyString)) {
			Map<String, Object> ts = JSON.parseObject(bodyString);
			r = formatToMap(ts);
		}
		return r;

	}

	/**
	 * 处理GET请求
	 * @param request /
	 * @return /
	 */
	public static Map<String, String[]> getParamMap(HttpServletRequest request) {
		HashMap<String, String[]> hashMap = new HashMap<>(4);
		String result;
		try {
			result = request.getQueryString();
			String regex = "codeParams=";
			// 加密
			if (result != null) {
				if (result.contains(regex)) {
					result = result.replace(regex, "");
					String desEncrypt = EncryptUtil.desEncrypt(result);
					// 转码manage.js中parseParam的编码
					desEncrypt = URLDecoder.decode(desEncrypt, "UTF-8");
					Map<String, Object> map = paramToMap(desEncrypt);
					for (String mapKey : map.keySet()) {
						hashMap.put(mapKey, new String[]{map.get(mapKey).toString()});
					}
				} else {
					// 非加密
					String[] query = result.split("&");
					for (String param : query) {
						String[] temp = param.split("=");
						hashMap.put(temp[0], new String[] {URLDecoder.decode(temp[1], "UTF-8")});
					}
				}
			}
		} catch (Exception e) {
			e.getStackTrace();
			log.info("GET请求参数解析异常");
		}
		return hashMap;
	}

	/**
	 * GET参数封装Map
	 * @param urlParam 参数
	 * @return Map<String, Object>
	 */
	private static Map<String, Object> paramToMap(String urlParam) {
		Map<String, Object> map = new HashMap<>(4);
		String[] param =  urlParam.split("&");
		for(String key : param){
			String[] pair = key.split("=");
			if(pair.length == 2){
				map.put(pair[0], pair[1]);
			}
		}
		return map;
	}

	/**
	 * POST/PUT参数封装Map
	 * @param data /
	 * @return /
	 */
	private static HashMap<String, String[]> formatToMap(Map<String, Object> data) {
		HashMap<String, String[]> hashMap = new HashMap<>(4);
		for (String mapKey : data.keySet()) {
			hashMap.put(mapKey, new String[]{data.get(mapKey) == null ? null : data.get(mapKey).toString()});
		}
		return hashMap;
	}

	private static boolean isJson(String content) {
		if (StringUtils.isBlank(content)) {
			return false;
		}
		boolean isJsonObject = true;
		boolean isJsonArray = true;
		try {
			JSONObject.parseObject(content);
		} catch (Exception e) {
			isJsonObject = false;
		}
		try {
			JSONObject.parseArray(content);
		} catch (Exception e) {
			isJsonArray = false;
		}
		// 不是json格式
		return isJsonObject || isJsonArray;
	}
}
